<template>
  <view class="w100 bg-gray flex-sub flex flex-col">
    <userList v-if="isAdmin">
      <u-button
        style="flex: 0; margin: 0"
        type="warning"
        size="mini"
        :color="$u.color.error"
        @click="showConfirm = true"
      >
        <view class="text-sm">登出</view>
      </u-button>
      <u-modal
        :show="showConfirm"
        title="提示"
        content="确认登出？"
        showCancelButton
        @confirm="logout"
        @cancel="showConfirm = false"
      ></u-modal
    ></userList>
    <template v-else>
      <u-navbar
        v-if="isSub"
        :safeAreaInsetTop="true"
        title="下级数据"
        :fixed="true"
        :autoBack="true"
        left-text="返回"
      >
      </u-navbar>

      <view
        :style="{ 'margin-top': isSub ? '30px' : '0' }"
        class="bg-gray w100 flex-sub flex-col"
      >
        <view
          :style="{ top: isSub ? '30px' : '0' }"
          class="top-pine w100 padding bg-blue text-df"
        >
          <view class="padding flex text-white">
            <view class="flex-sub flex">
              <uni-icons
                color="u-primary-light"
                type="staff-filled"
                size="20"
              ></uni-icons>

              <view class="text-lg">{{ info.account }}</view>
              <u-button
                style="margin-left: 10px; flex: 0"
                icon="reload"
                icon-color="#fff"
                type="info"
                size="mini"
                :color="$u.color.primary"
                @click="refresh"
              ></u-button>
            </view>

            <view class="flex" style="gap: 10px">
              <u-button
                style="flex: 0; margin: 0"
                type="warning"
                size="mini"
                :color="$u.color.error"
                @click="showConfirm = true"
              >
                <view class="text-sm">登出</view>
              </u-button>
              <u-button
                v-if="!this.isAdmin"
                style="flex: 0; margin: 0"
                type="primary"
                size="mini"
                :color="$u.color.error"
                @click="changeCurPorStatus"
              >
                <view class="text-sm" style="white-space: pre">{{
                 curProStatus  === "pdd" ? "拼多多" :curProStatus  === "jd" ?"京东": "淘宝"
                }}</view>
              </u-button>

            </view>
          </view>
          <view class="w100 grid col-2">
            <view class="text-sm" style="background-color: #f56c6c;text-align: center;padding: 5px 5px;margin: 0 auto;border-radius: 3px;" @click="productClick">
              {{product_name}}
            </view>
          </view>
          <view class="w100 grid col-2">
            <view class="padding margin-bottom flex-col">
              <view class="text-gray">账户余额</view>
              <view class="text-xxl margin-top-sm w100 text-cut">
                <u-count-to
                  color="#fff"
                  :startVal="0"
                  :endVal="info.cash"
                  separator=","
                ></u-count-to>
              </view>
            </view>
            <view class="padding margin-bottom flex-col align-end">
              <view class="text-gray">日消耗</view>
              <view class="text-xxl margin-top-sm w100 text-cut text-right">
                <u-count-to
                  color="#fff"
                  :startVal="0"
                  :endVal="info.cost"
                  separator=","
                ></u-count-to
              ></view>
            </view>
          </view>
        </view>
        <view
          style="margin-top: -50px"
          class="ctx padding w100 flex-col text-df"
        >
          <view class="bg-white padding bd-r">
            <view class="flex justify-between">
              <view class="text-bold">数据概览 </view>
              <u-tag
                :text="dataPicker"
                type="info"
                size="mini"
                @click="showPicker = true"
              />
            </view>
            <view
              class="grid col-3"
              @click="handleClickData"
              style="position: relative"
            >
              <u-icon
                v-if="roleId != 5"
                class="data-icon"
                name="arrow-right"
                color="#007aff"
              ></u-icon>
              <view
                class="flex-col align-center padding-top"
                v-for="(item, index) in dataMapList"
                :key="index"
              >
                <view
                  :class="{ 'text-center': roleId == 5 }"
                  class="w100"
                  v-for="(value, key) in item"
                  :key="key"
                >
                  <view class="text-df">{{ value }}</view>
                  <view
                    :class="{ 'text-blue': roleId !== 5 }"
                    class="text-df w100 margin-top-sm text-bold text-cut"
                    >{{ summary[key] }}</view
                  >
                </view>
              </view>
            </view>
          </view>

          <view
            class="bg-white padding bd-b"
            :class="{
              'margin-top-sm': !index,
              'bd-r-t': !index,
              'bd-r-b': index === graphList.length - 1,
            }"
            v-for="(item, index) in graphList"
            :key="index"
          >
            <view v-if="!index" class="flex padding-tb justify-between">
              <view class="text-bold">趋势</view>
            </view>
            <Uchart :chartData="item"></Uchart>
          </view>
        </view>
        <u-picker
          :show="showPicker"
          :columns="columns"
          :value="dataPicker"
          closeOnClickOverlay
          @confirm="dataPickerConfirm"
          @cancel="dataPickerClose"
          @close="dataPickerClose"
        ></u-picker>

          <u-picker
                  keyName="name"
                  :show="showProduct"
                  :columns="columnProduct"
                  closeOnClickOverlay
                  @close="showProduct = false"
                  @cancel="showProduct = false"
                  @confirm="handleProduct"
          ></u-picker>
      </view>
      <u-modal
        :show="showConfirm"
        title="提示"
        content="确认登出？"
        showCancelButton
        @confirm="logout"
        @cancel="showConfirm = false"
      ></u-modal>
    </template>
  </view>
</template>

<script>
import { indexData, indexShow, indexGraph,getProductList} from "@/api";
import dayjs from "dayjs";
import Uchart from "./uchart.vue";
import UniIcons from "@/components/uni-icons/uni-icons";

import { mapGetters } from "vuex";
import userList from "./sub/userList.vue";
export default {
  components: {
    Uchart,
    UniIcons,
    userList,
  },
  props: {
    isSub: {
      type: Boolean,
      default: false,
    },
    sonId: {
      type: String | Number,
    },
    queryDate: {
      type: String,
    },
      productName: {
          type: String,
      },
      productId:{
          type: String | Number,
      }
  },
  data() {
    return {
      showConfirm: false,
      scrollTop: 0,
      roleId: "",
      info: {
        account: "",
        cost: 0,
        cash: 0,
      },
      graphList: [],
      showPicker: false,
        showProduct:false,
        product_id:0,
        product_name:"全部产品",
      dataMapList: [
        { cost: "总消耗" },
        { sales: "总销售" },
        { effective_sales: "有效销售" },
        { order_num: "订单数" },
        { ROI: "ROI" },
        { effective_ROI: "有效ROI" },
      ],
      summary: {},
      columns: [["今日", "昨日", "本周", "上周", "本月", "上月"]],
      columnProduct:[],
      dataPicker: "今日",
    };
  },
  computed: {
    ...mapGetters(["isAdmin", "curProStatus"]),

    dateParams() {
      let start_date;
      let end_date = dayjs().format("YYYY-MM-DD");
      switch (this.dataPicker) {
        case "今日":
          start_date = dayjs().format("YYYY-MM-DD");
          break;
        case "昨日":
          start_date = end_date = dayjs()
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          break;
        case "本周":
          start_date = dayjs()
            .subtract((dayjs().day() || 7) - 1, "day")
            .format("YYYY-MM-DD");
          break;
        case "本月":
          start_date = dayjs().format("YYYY-MM-01");
          break;
        case "上周":
          start_date = dayjs().subtract(7, "day").format("YYYY-MM-DD");
          break;
        case "上月":
          // 获取上个月的第一天
          const firstDayOfLastMonth = dayjs()
            .subtract(1, "month")
            .startOf("month")
            .format("YYYY-MM-DD");

          // 获取上个月的最后一天
          const lastDayOfLastMonth = dayjs()
            .subtract(1, "month")
            .endOf("month")
            .format("YYYY-MM-DD");

          // 打印结果
          // console.log(`上个月的第一天：${firstDayOfLastMonth}`);
          // console.log(`上个月的最后一天：${lastDayOfLastMonth}`);
          start_date = firstDayOfLastMonth;
          end_date = lastDayOfLastMonth;
          break;
        default:
          start_date = dayjs().format("YYYY-MM-DD");
          break;
      }
      return {
        start_date,
        end_date,
      };
    },
  },
  getDay(year, month) {
    var firstDay = new Date(year, month - 1, 1); //这个月的第一天
    var currentMonth = firstDay.getMonth(); //取得月份数
    var lastDay = new Date(firstDay.getFullYear(), currentMonth + 1, 0); //是0而不是-1

    var fy = firstDay.getFullYear(); //获取年份
    var fm = firstDay.getMonth() + 1; //获取月份
    firstDay = [fy, fm, "01"].join("-");

    var ly = lastDay.getFullYear(); //获取年份
    var lm = lastDay.getMonth() + 1; //获取月份
    var ld = lastDay.getDate();
    lastDay = [ly, lm, ld].join("-");

    return [firstDay, lastDay];
  },
  onPageScroll(e) {
    console.log(e, 111);
    this.scrollTop = e.scrollTop;
  },
  onLoad() {
      const userInfo = uni.getStorageSync("__userInfo__");
      const product = uni.getStorageSync("product");
      if (product) {
          this.product_id = product.product_id;
          this.product_name = product.product_name;
          let product_content={
              product_id:this.product_id,
              product_name:this.product_name
          }
          this.$store.commit("product", product_content);
          this.queryDate=product.dataPicker;
          if(product.sonId!=null){
              uni.navigateTo({
                  url: `/pages/index/sub/subIndex?sonId=${product.sonId ?? ""}&queryDate=${
                      product.dataPicker
                      }&productId=${this.product_id}&productName=${this.product_name}`,
              });
          }
      }
      uni.removeStorageSync("product");
      console.log("product", product);
      console.log("userInfo", userInfo);
      
    if (!userInfo) {
      return uni.redirectTo({
        url: "/pages/login/index",
      });
    }
    this.roleId = userInfo?.role;
    let status = uni.getStorageSync("curProStatus");
    this.$store.commit("SET_CUR_PRO_STATUS", status);
    this.$store.commit("SET_USER_INFO", userInfo);

    console.log("curProStatus1", this.curProStatus, status);

    if (this.isAdmin) {
      // uni.setTabBarItem({ index: 1, visible: true }); //管理员看不到商品
      uni.setTabBarItem({ index: 4, visible: false }); //管理员看不到评论
      uni.setTabBarItem({ index: 6, visible: true }); //非管理员看不到转账
    }
    if (!this.isAdmin) {
      uni.setTabBarItem({ index: 1, visible: false }); //非管理员看不到商品
      uni.setTabBarItem({ index: 6, visible: false }); //非管理员看不到转账
      uni.setTabBarItem({ index: 4, visible: true }); //管理员看不到评论
    }
  },
  mounted() {
    if (this.isAdmin) return;
    console.log("queryDate===", this.queryDate);
    this.dataPicker = this.queryDate || "今日";
    if(this.sonId){
        this.product_id = Number(this.productId )|| 0;
        this.product_name = this.productName || "全部产品";
    }
    this.refresh();
  },
  onPullDownRefresh() {
    this.refresh().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    logout() {
      this.showConfirm = false;
      uni.setStorageSync("__userInfo__", "");
      return uni.reLaunch({
        url: "/pages/login/index",
      });
    },
    changeCurPorStatus() {
      this.$store.commit(
        "SET_CUR_PRO_STATUS",
        this.curProStatus == "pdd" ? "tb":this.curProStatus == "tb"?"jd":"pdd"
      );
      window.location.reload();
    },
      productClick(){
        this.showProduct=true;
          getProductList({
              page:1,
              page_size:9999
          }).then((r) => {
              let list=[{ id: 0, name: "全部产品" }];
              this.columnProduct=[list.concat(r.data.list)];
              console.log(r);
          }).catch((e) => {
              console.error(e);
          });
      },
    refresh() {
      return Promise.all([
        this.getInfo(),
        this.getIndexData(),
        this.getIndexGraph(),
      ]);
    },
    handleClickData() {
      if (this.roleId == 5) return;
      uni.navigateTo({
        url: `/pages/index/sub/userList?sonId=${this.sonId ?? ""}&queryDate=${
          this.dataPicker
        }`,
      });
    },
    handleProduct(val){
        console.log(window.location.href);
        let url=window.location.href;
        let product={
            product_id:val.value[0].id,
            product_name:val.value[0].name,
            sonId:this.sonId,
            dataPicker:this.dataPicker
        };
        uni.setStorageSync("product", product);
        delete product.sonId;
        delete product.dataPicker;
        this.$store.commit("product", product);
        console.log(this.$store.state.product);
        window.open(url)
        // console.log(val.value[0]);
        // this.product_id=val.value[0].id;
        // this.product_name=val.value[0].name;
        this.showProduct=false;
        // this.getIndexGraph();
        // this.getIndexData();
    },
    getIndexGraph() {
      indexGraph({
        product_id:this.product_id,
        channel: this.isAdmin ? 0 : this.curProStatus == "pdd" ? 1 :this.curProStatus == "jd"?4: 3,
        son_id: +this.sonId,
        datetime: dayjs().format("YYYY-MM-DD"),
        refer_datetime: dayjs().subtract(1, "day").format("YYYY-MM-DD"),
      })
        .then((r) => {
          console.log(1111, r);
          const attrMap = {
            cost_graph: "今日消耗",
            refer_cost_graph: "昨日消耗",

            effect_refer_roi_graph: "昨日有效ROI",
            effect_roi_graph: "今日有效ROI",

            refer_sale_graph: "昨日销售",
            sale_graph: "今日销售",
          };
          const obj = r.data;
          if(obj.advertiser_num!=undefined){
              delete obj.advertiser_num;
          }
            if(obj.cash_num!=undefined){
                delete obj.cash_num;
            }
            if(obj.click_cost_num!=undefined){
                delete obj.click_cost_num;
            }
            if(obj.click_num!=undefined){
                delete obj.click_num;
            }
            if(obj.convert_cost_num!=undefined){
                delete obj.convert_cost_num;
            }
            if(obj.convert_num!=undefined){
                delete obj.convert_num;
            }
            if(obj.cost_num!=undefined){
                delete obj.cost_num;
            }
            if(obj.promotion_ok_num!=undefined){
                delete obj.promotion_ok_num;
            }
            if(obj.show_num!=undefined){
                delete obj.show_num;
            }
            if(obj.roi!=undefined){
                delete obj.roi;
            }
          Object.keys(obj).forEach((k) => {
              obj[k].name = attrMap[k];
            obj[k].x = obj[k]?.x?.map((i, idx) => (idx % 3 ? "" : `${+i}点`));
            obj[k].y = obj[k]?.y;
          });

          const {
            cost_graph,
            refer_cost_graph,

            effect_refer_roi_graph,
            effect_roi_graph,

            refer_sale_graph,
            sale_graph,
          } = obj;
          this.graphList = [
            [cost_graph, refer_cost_graph],
            [effect_roi_graph, effect_refer_roi_graph],
            [sale_graph, refer_sale_graph],
          ].map((i) => {
            const [today, yesterday] = i;
            return {
              categories: today.x,
              series: [
                {
                  name: today.name,
                  data: today.y,
                },
                {
                  name: yesterday.name,
                  data: yesterday.y,
                },
              ],
            };
          });
          console.log("this.graphList", this.graphList);
        })
        .catch((e) => {
          console.error(e);
        });
    },
    getIndexData() {
      return Promise.all([
        indexData({
          product_id:this.product_id,
          channel: this.isAdmin ? 0 : this.curProStatus == "pdd" ? 1 :this.curProStatus == "jd"?4: 3,
          son_id: +this.sonId,
          ...this.dateParams,
        }).then((r) => {
          this.summary = r.data;
        }),
      ]);
    },
    getInfo() {
      return indexShow({
        channel: this.isAdmin ? 0 : this.curProStatus == "pdd" ? 1 :this.curProStatus == "jd"?4: 3,
        son_id: +this.sonId,
      }).then((r) => {
        this.info = r.data;
        this.roleId = r.data.role;
      });
    },
    dataPickerConfirm(e) {
      this.showPicker = false;

      this.dataPicker = e?.value?.[0];
      this.$nextTick(() => {
        this.getIndexData();
      });
    },
    dataPickerClose() {
      this.showPicker = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.top-pine {
  position: sticky;
  top: 0;
}
.ctx {
  z-index: 1;
}
.data-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16px !important;
  color: $uni-color-primary;
}
</style>
